package com.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.entity.Result;
import com.changgou.goods.feign.SkuFeign;
import com.changgou.goods.pojo.Sku;
import com.changgou.search.pojo.SkuInfo;
import com.search.dao.ESManagerMapper;
import com.search.service.EsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
@Transactional
public class EsServiceImpl implements EsService {
    @Autowired
    private SkuFeign skuFeign;
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;
    @Autowired
    private ESManagerMapper esManagerMapper;
    @Override
    public void importAll() {
        List<Sku> all = skuFeign.findAllSku();
        String jsonString = JSON.toJSONString(all);
        List<SkuInfo> skuInfoList = JSON.parseArray(jsonString, SkuInfo.class);
        for (SkuInfo skuInfo : skuInfoList) {
            Map map = JSON.parseObject(skuInfo.getSpec(), Map.class);
            skuInfo.setSpecMap(map);
        }
        esManagerMapper.saveAll(skuInfoList);
    }

    @Override
    public void createIndex() {
        elasticsearchTemplate.createIndex(SkuInfo.class);
        elasticsearchTemplate.putMapping(SkuInfo.class);
    }

    @Override
    public void delete(String spuid) {
        List<Sku> skuList= skuFeign.findBySpuId(spuid);
        if (skuList==null||skuList.size()==0){
            System.out.println("查不到数据"
            );
            return;
        }
        for (Sku sku : skuList) {
            esManagerMapper.deleteById(Long.parseLong(sku.getId()));
        }

    }
}
